package org.filetransfer.file_transfer_java_backend.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.filetransfer.file_transfer_java_backend.entity.User;
import org.filetransfer.file_transfer_java_backend.repository.UserRepository;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.time.Instant;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class DataInitializer {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Bean
    public ApplicationRunner initializeData() {
        return args -> {
            // Create default admin user if not exists
            if (!userRepository.existsByUsername("admin")) {
                User admin = User.builder()
                        .username("admin")
                        .email("admin@filetransfer.com")
                        .password(passwordEncoder.encode("admin123"))
                        .displayName("系统管理员")
                        .role(User.Role.ADMIN)
                        .enabled(true)
                        .createdAt(Instant.now())
                        .build();
                
                userRepository.save(admin);
                log.info("默认管理员账户创建成功: admin / admin123");
            }
            
            // Create default test user if not exists
            if (!userRepository.existsByUsername("testuser")) {
                User testUser = User.builder()
                        .username("testuser")
                        .email("test@filetransfer.com")
                        .password(passwordEncoder.encode("test123"))
                        .displayName("测试用户")
                        .role(User.Role.USER)
                        .enabled(true)
                        .createdAt(Instant.now())
                        .build();
                  userRepository.save(testUser);
                log.info("默认测试用户创建成功: testuser / test123");
            }
            
            // Create guest user if not exists
            if (!userRepository.existsByUsername("guest")) {
                User guestUser = User.builder()
                        .username("guest")
                        .email("guest@filetransfer.com")
                        .password(passwordEncoder.encode("guest123"))
                        .displayName("游客用户")
                        .role(User.Role.USER)
                        .enabled(true)
                        .createdAt(Instant.now())
                        .build();
                
                userRepository.save(guestUser);
                log.info("游客用户创建成功: guest");
            }
        };
    }
}
